<?php

class MusicController extends Controller {
    public function init() {
        $this->layout = 'contents';
    }
    const PAGE_SIZE=10;

    /**
     * @var string specifies the default action to be 'index'.
     */
    public $defaultAction = 'index';

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow',  // allow all users to perform 'index' and 'show' actions
                'actions' => array('index', 'show', 'changeStatus', 'changeRecommend', 'changePicking'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'batchProcess'),
                'users' => array('admin'),
            ),
            array('deny',  // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionChangeOrderPos() {
        if (Yii::app()->request->isPostRequest) {
            $id = Yii::app()->request->getPost('id');
            $value = Yii::app()->request->getPost('value');
            return (Music::model()->updateByPk($id, array('order_pos' => $value)))
                ? $value
                : 'error';
        }
    }

    // change status
    public function actionChangeStatus() {
        if (Yii::app()->request->isAjaxRequest) {
            $id = Yii::app()->request->getPost('id');
            $model = Music::model()->findByPk($id);
            switch ($model->status) {
                case Options::STATUS_DRAFT:
                    $status = Options::STATUS_PUBLISHED; break;
                case Options::STATUS_PUBLISHED:
                    $status = Options::STATUS_DRAFT; break;
                default:
                    $status = Options::STATUS_PENDING_DELETE;
            }
            $model->status = $status;
            try {
                $model->save(false);
            } catch (Exception $ex) {
                echo $ex;
            }

            echo $model->statusIconFormat;
        }
    }

    /**
     * change "is_recommend" value, false or true
     */
    public function actionChangeRecommend() {
        if (Yii::app()->request->isAjaxRequest) {
            $id = Yii::app()->request->getPost('id');
            $model = Music::model()->findByPk($id);
            $value = (intval($model->is_recommend))
                ? Options::RECOMMEND_NO
                : Options::RECOMMEND_YES;
            $model->is_recommend = $value;
            try {
                $model->save(false);
            } catch (Exception $ex) {
                echo $ex;
            }

            echo $model->isRecommendIconFormat;
        }
    }

    /*
     * change "is_picking" value, false or true
     */
    public function actionChangePicking() {
        if (Yii::app()->request->isAjaxRequest) {
            $id = Yii::app()->request->getPost('id');
            $model = Music::model()->findByPk($id);
            $value = (intval($model->is_picking))
                ? Options::PICKING_NO
                : Options::PICKING_YES;
            $model->is_picking = $value;
            try {
                $model->save(false);
            } catch (Exception $ex) {
                echo $ex;
            }

            echo $model->isPickingIconFormat;
        }
    }

    /**
     * Shows a particular model.
     */
    public function actionShow() {
        $this->render('show',array('model' => $this->loadMusic()));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'show' page.
     */
    public function actionCreate() {
        $model = new Music;
        if (isset($_POST['Music'])) {
            $model->attributes = $_POST['Music'];
            if ($model->save()) {
                $this->redirect(array('index', 'node' => $_POST['Music']['node_id']));
            }
        }
        $this->render('create', array('model' => $model));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'show' page.
     */
    public function actionUpdate() {
        $model = $this->loadMusic();
        if (isset($_POST['Music'])) {
            $model->attributes = $_POST['Music'];
            if ($model->save()) {
                $this->redirect(array('index', 'node' => $_POST['Music']['node_id']));
            }
        }
        $this->render('update',array('model'=>$model));
    }

    // 批量更新
    public function actionBatchProcess() {
        if (Yii::app()->request->isPostRequest) {
            $action = strtolower(trim(Yii::app()->request->getPost('action_list')));
            switch ($action) {
                case 'update_order_pos':
                    $order_pos = Yii::app()->request->getPost('order_pos');
                    if (!empty($order_pos)) {
                        foreach ($order_pos as $key => $value) {
                            Music::model()->updateByPk($key, array('order_pos' => $value));
                        }
                    }
                    break;
                case 'delete_selected':
                    $select = Yii::app()->request->getPost('select');
                    if (!empty($select)) {
                        foreach ($select as $id) {
                            $model = Music::model()->findByPk($id)->delete();
                        }
                    }
                    break;
                case 'move_to_recycle_bin':
                    $select = Yii::app()->request->getPost('select');
                    if (!empty($select)) {
                        foreach ($select as $id) {
                            $model = Music::model()->updateByPk($id, array(
                                'status' => Options::STATUS_PENDING_DELETE));
                        }
                    }
                    break;
            }

            $this->redirect(array('index', 'node' => Yii::app()->request->getPost('current_node')));
        } else {
            throw new CHttpException(400, Yii::t('common', 'invalid_request'));
        }
    }

    /**
     * index
     */
    public function actionIndex() {
        $current_node = Yii::app()->request->getParam('node');
        $criteria = new CDbCriteria;
        $criteria->condition = 'status != ' . Options::STATUS_PENDING_DELETE;
        if (intval($current_node)) {
            $criteria->addCondition("node_id = {$current_node}");
        }

        $pages = new CPagination(Music::model()->count($criteria));
        $pages->pageSize = self::PAGE_SIZE;
        $pages->applyLimit($criteria);

        $sort = new CSort('Music');
        $sort->applyOrder($criteria);

        $models = Music::model()->findAll($criteria);

        $this->render('index',array(
            'models' => $models,
            'pages' => $pages,
            'sort' => $sort,
            'current_node' => $current_node,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
     */
    public function loadMusic($id=null) {
        if($this->_model===null) {
            if($id!==null || isset($_GET['id']))
                $this->_model=Music::model()->findbyPk($id!==null ? $id : $_GET['id']);
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }
        return $this->_model;
    }

    /**
     * Executes any command triggered on the admin page.
     */
    protected function processAdminCommand() {
        if(isset($_POST['command'], $_POST['id']) && $_POST['command']==='delete') {
            $this->loadMusic($_POST['id'])->delete();
            // reload the current page to avoid duplicated delete actions
            $this->refresh();
        }
    }
}
